import os
import json
from vosk import Model, KaldiRecognizer
from src.config import MODEL_PATHS, AUDIO_SETTINGS


class SpeechRecognizer:
    """多语言语音识别引擎"""
    
    def __init__(self, language='en'):
        """
        初始化语音识别器
        :param language: 目标语言代码 (en, ja, de等)
        """
        if language not in MODEL_PATHS:
            raise ValueError(f"不支持的语言: {language}")
            
        model_path = MODEL_PATHS[language]
        if not os.path.exists(model_path):
            raise FileNotFoundError(f"请先下载 {language} 语言模型")
            
        self.model = Model(model_path)
        self.recognizer = KaldiRecognizer(self.model, AUDIO_SETTINGS['sample_rate'])
        self.partial_results = []

    def process_audio(self, audio_data):
        """
        处理音频数据并返回识别结果
        :param audio_data: PCM格式的音频数据
        :return: (完整结果, 临时结果)
        """
        # 转换为bytes格式
        audio_bytes = audio_data.tobytes()
        
        if self.recognizer.AcceptWaveform(audio_bytes):
            result = json.loads(self.recognizer.Result())
            return (result.get('text', ''), '')
        else:
            partial = json.loads(self.recognizer.PartialResult())
            return ('', partial.get('partial', '')) 